<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="月份" prop="routesName">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          value-format="yyyy-MM"
          @change="handleChange"
          :clearable="false"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['task:calendar:edit']"
          @click="handleAdd(0)"
          >新增任务</el-button
        >
      </el-form-item>
    </el-form>

    <div class="w-table">
      <table class="w-calendar">
        <thead>
          <th>星期一</th>
          <th>星期二</th>
          <th>星期三</th>
          <th>星期四</th>
          <th>星期五</th>
          <th>星期六</th>
          <th>星期天</th>
        </thead>
        <tbody>
          <tr v-for="(items,index) in timeList" :key="index">
            <td v-for="(item,idx) in items" :key="idx" :class="{'goover':item.type == 1 }">
              <div class="w-box" @click="openDialog(item)">
                <div class="w-day"><img src="@/assets/images/today.png" alt="" v-if="today == item.date">{{item.day}}</div>
                <div class="w-task" v-for="data in item.list.slice(0,3)" :key="data.time">
                  <span class="w-time">{{parseTime(data.time,'{h}:{i}')}}</span>
                  <span class="w-name">{{data.name.length > 9 ? data.name.slice(0,9) + '...' : data.name }}</span>
                </div>
                <div class="w-task" v-if="item.list.length>3">
                  <span class="w-name" style="font-weight:700;">···</span>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
        <div class="w-dialog">
          <el-table :data="dataList" style="width: 100%;" height="100%">
              <el-table-column prop="name" align="center" label="任务名称" show-overflow-tooltip width="200"> </el-table-column>
              <el-table-column prop="taskDesc" align="center" label="任务描述" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="taskType" align="center" label="任务类型" show-overflow-tooltip> 
                <template slot-scope="scope" >
                  <span>{{scope.row.taskType | taskType}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="time" align="center" label="执行时间" show-overflow-tooltip> </el-table-column>
              <el-table-column prop="routesName" align="center" label="关联航线" show-overflow-tooltip width="180"> </el-table-column>
              <el-table-column label="操作" align="center"  width="250"  class-name="small-padding fixed-width" >
                <template slot-scope="scope">
                  <el-button v-hasPermi="['task:calendar:remove']" size="mini" v-show="scope.row.taskType == 1 || scope.row.taskType == 2"  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" >删除任务</el-button>
                  <!-- <el-button v-hasPermi="['task:calendar:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" >编辑任务</el-button> -->
                  <el-button v-hasPermi="['task:blacklist:edit']" size="mini" v-show="scope.row.taskType == 3"  type="text" icon="el-icon-delete" @click="handleRemove(scope.row)" >删除单次任务</el-button>
                  <el-button v-hasPermi="['task:calendar:remove']" size="mini" v-show="scope.row.taskType == 3"  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" >删除关联任务</el-button>
                </template>
              </el-table-column>
            </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">关闭</el-button>
        </div>
      </el-dialog>
  </div>
</template>
    
  <script>
// import { routesList, DeleteRoutes } from "@/api/cruise/airline";
import { TaskMonthTaskList, removeTask, deleteTask } from "@/api/cruise/task";
import { parseTime } from "@/utils/ruoyi";
// import { listAirport } from "@/api/cruise/airdrome";
export default {
  name: "Dict",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 预案表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        month: parseTime(new Date(), "{y}-{m}"),
      },
      openAdd: false,
      airportList: [],
      timeList: [], // 日历日期列表
      week: 1,
      today: parseTime(new Date(),"{y}-{m}-{d}"),
      open: false,
      dataList: [],
      title: ""
    };
  },
  created() {
    this.getCalendar();
  },
  methods: {
    handleRemove(data){
      let params = {
        taskId: data.task,
        taskExecTime: data.time
      }
      removeTask(params).then(res => {
        console.log(res)
        this.getCalendar();
        let index = this.dataList.findIndex(item => (item.task == data.task) && (item.time == data.time))
        this.dataList.splice(index,1)
        this.$modal.msgSuccess("删除成功");
      })
    },
    handleUpdate(data){
      this.handleAdd(data.task)
    },
    openDialog(data){
      console.log("data",data)
      if(data.list.length != 0) {
        this.open = true
        this.dataList = data.list
        this.title = data.date
      }
    },
    handleChange() {
      this.getCalendar();
    },
    getTaskMonthTaskList(arr) {
      TaskMonthTaskList(this.queryParams).then((res) => {
        console.log("任务列表", res);
        let data = res.data || []
        data.forEach(item => {
          let index = arr.findIndex(val => val.date == item.date)
          if(index != 0) {
            arr[index].list = item.task
          }
        });
        this.timeList = this.arrayChunk(arr,7)
      });
    },
    getCalendar() {
      this.timeList = [];
      let arr = []
      let date = new Date(this.queryParams.month + "-01" + " 00:00:00");
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let day = date.getDay() == 0? 7 : date.getDay();
      let lastD = this.getLastDay(y, m);
      this.week = day;
      if(day != 1) {
        for(let i=1;i<day;i++) {
          let obj = {
            date: parseTime((date.getTime() - 864e5 * i),"{y}-{m}-{d}"),
            day: new Date(date.getTime() - 864e5 * i).getDate(),
            type: 0,
            list: []
          };
          arr.unshift(obj);
        }
      }
      for (let i = d; i <= lastD; i++) {
        let obj = {
          date: y + "-" + (m > 9 ? m : "0" + m) + "-" + (i > 9 ? i : "0" + i),
          day: i,
          type: 1,
          list: []
        };
        arr.push(obj);
      }
      let differ = arr.length % 7
      if(differ != 0) {
        for(let i=1;i<=(7-differ); i++) {
          let timestamp = new Date(this.queryParams.month + "-" + lastD + " 00:00:00").getTime()
          let obj = {
            date: parseTime((timestamp + 864e5 * i),"{y}-{m}-{d}"),
            day: new Date(timestamp + 864e5 * i).getDate(),
            type: 2,
            list: []
          };
          arr.push(obj);
        }
      }
      this.getTaskMonthTaskList(arr);
    },
    // 获取月份天数
    getLastDay(year, month) {
      if (month != 2) {
        if (month == 4 || month == 6 || month == 9 || month == 11)
          //判断月是30天还是31天,2月除外
          return 30;
        else return 31;
      } else {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
          //判断是否是闰年，进行相应的改变
          return 29;
        else return 28;
      }
    },
    // 数组拆分
    arrayChunk(array,size) {
      let data = []
      for (let i = 0; i < array.length; i += size) {
        data.push(array.slice(i, i + size))
      }
      return data
    },

    // getAirport(){
    //     listAirport({pageNum: 1,pageSize: 999}).then(res => {
    //         console.log("机场列表",res)
    //         this.airportList = res.rows || []
    //     })
    // },
    submitForm() {
      this.$refs["addform"].validate((valid) => {
        if (valid) {
          this.$router.push({
            path: "/cruise/airline-edit/edit/0",
            query: {
              routesName: this.addform.routesName,
              airportId: this.addform.airportId,
            },
          });
        }
      });
    },
    cancel() {
      this.open = false;
    },
    /** 新增按钮操作 */
    handleAdd(id) {
      this.$router.push("/cruise/task-edit/edit/"+ id);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除任务名称为"' + row.name + '"的数据项？')
        .then(function () {
          return deleteTask(row.task);
        })
        .then(() => {
          this.open = false
          this.getCalendar();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
  filters: {
    taskType(val) {
      if(val == 1) {
        return "立即任务";
      } else if(val == 2) {
        return "定时任务";
      } else {
        return "循环任务";
      }
    }
  }
};
</script>
    
<style lang="scss" scoped>
.w-table {
  width: 100%;
}
.w-calendar {
  width: 100%;
  height: auto;
  border-collapse: collapse; 
  thead {
    width: 100%;
    height: 40px;
    th {
      font-size: 14px;
      font-weight: 400;
      border-bottom: 1px solid #ebeef5;
      height: 40px;
    }
  }
  
  td {
    width: 14.28%;
    border-bottom: 1px solid #ebeef5;
    border-right: 1px solid #ebeef5;
    font-weight: 400;
    padding: 8px;
    color: #c0c4cc;
    &:nth-child(1) {
      border-left: 1px solid #ebeef5;
    }
    .w-box {
      height: 120px;
      cursor: pointer;
      .w-day {
        display: flex;
        align-items: center;
        height: 30px;
        justify-content: center;
        img{
          width: 20px;
        }
      }
      .w-task {
        text-align: left;
        font-size: 13px;
        height: 25px;
        line-height: 25px;
        .w-time {
          color: #8b8686;
        }
        .w-name {
          margin-left: 5px;
        }
      }
    }
  }
  .goover {
      color:#000;
    }
  td:hover {
    background: #f2f8fe;
  }
  
}

.w-dialog {
  width: 100%;
  height: 400px;
}
</style>